// Wordreference API Key 5c25c
// http://www.wordreference.com/docs/api.aspx

// Esempio
// http://api.wordreference.com/5c25c/json/iten/folletto

const St = imports.gi.St;
const Lang = imports.lang;
const Main = imports.ui.main;
const Search = imports.ui.search;
const SearchDisplay = imports.ui.searchDisplay;
const IconGrid = imports.ui.iconGrid;

const Gio = imports.gi.Gio;

const ICON_SIZE = imports.ui.contactDisplay.ICON_SIZE;
const MAX_SEARCH_RESULTS_ROWS = imports.ui.contactDisplay.MAX_SEARCH_RESULTS_ROWS;

let wordRefProvider;

const WordRefResult = new Lang.Class({
	Name: "WordRefResult",
    _init: function(resultMeta) {
        this.actor = new St.Bin({style_class: 'contact',
                                 reactive: true,
                                 track_hover: true});

        let content = new St.BoxLayout({style_class: 'contact-content',
                                        vertical: false });
        this.actor.set_child(content);

        let icon = new St.Icon({icon_type: St.IconType.FULLCOLOR,
                                icon_size: ICON_SIZE,
                                icon_name: 'accessories-dictionary',
                                style_class: 'contact-icon'});

        content.add(icon, {x_fill: true,
                           y_fill: false,
                           x_align: St.Align.START,
                           y_align: St.Align.MIDDLE});

        let result = new St.BoxLayout({style_class: 'contact-details',
                                       vertical: true});

        content.add(result, {x_fill: true, x_align: St.Align.START});

        let exprLabel = new St.Label({text: resultMeta.expr,
                                      style_class: 'result-expr'});
        let resultLabel = new St.Label({text: resultMeta.result,
                                        style_class: 'result-result'});

        result.add(exprLabel, {x_fill: false, x_align: St.Align.START});
        result.add(resultLabel, {x_fill: false, x_align: St.Align.START});
    }

});

const WordRefProvider = new Lang.Class({
	Name: 'WordRefProvider',
	Extends: Search.SearchProvider,

	_init: function(title) {
		this.parent(title);
	},

	getInitialResultSet: function(terms) {
		let query = terms.join(" ");
		let engines = [/^enit/, /^iten/];
		
		var enter = false;
		for (var i in engines)
			if (engines[i].test(terms[0]))
				enter = true;

    	if (enter && terms[1]) {
    		var key = "5c25c";
    		var uri = "http://api.wordreference.com/"
    				+ key + "/json/" + terms[0] + "/" + terms[1];
    		global.log("Getting uri: " + uri);
		  	var cont = Gio.file_new_for_uri(uri).load_contents(null);

		  	if (!cont[0])
		  		return [];
		  	var jobj = JSON.parse(cont[1]);

			var synon = "";

			var t0 = jobj["term0"];
			for (var tr in t0) {
				synon += t0[tr][0]["FirstTranslation"]["term"] + " ";
			}

 	 		return [{'expr': terms[0], "result": synon}];
		}
		else
			return [];
    },

    getSubsearchResultSet: function(prevResults, terms) {
        return this.getInitialResultSet(terms);
    },

    getResultMetas: function(ids) {
        let metas = [];
        for (let i = 0; i < ids.length; i++) {
            metas.push({'id': ids[i],
                        'name': '',
                        'createIcon': ''});
        }
        return metas;
    },

    createResultActor: function(resultMeta, terms) {
        let result = new WordRefResult(resultMeta.id);
        return result.actor;
    },

    createResultContainerActor: function() {
        let grid = new IconGrid.IconGrid({rowLimit: MAX_SEARCH_RESULTS_ROWS,
                                          xAlign: St.Align.START });
        grid.actor.style_class = 'contact-grid';

        let actor = new SearchDisplay.GridSearchResults(this, grid);
        return actor;
    },

    activateResult: function(resultId) {
        return true;
    }
});

function init() {
	wordRefProvider = new WordRefProvider("WORD REFERENCE");
}

function enable() {
    Main.overview.addSearchProvider(wordRefProvider);
}

function disable() {
    Main.overview.removeSearchProvider(wordRefProvider);
}

